namespace ResumableDownload.View.Converters
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using WP7Contrib.Services.DownloadManager;

    public sealed class BlockSizeToStringConverter : IValueConverter
    {
        private const int KiloByte = 1024;

        public static NumberFormatInfo nfi;
        public static NumberFormatInfo nfiPercentage;

        public readonly string BlockSizeFormat = "Block: {0} Kb";

        static BlockSizeToStringConverter()
        {
            nfi = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
            nfi.NumberDecimalDigits = 0;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var downloader = value as IDownloadService;

            if (downloader == null || value == DependencyProperty.UnsetValue)
            {
                return DependencyProperty.UnsetValue;
            }

            if (downloader.State == DownloaderState.Ready ||
                downloader.State == DownloaderState.Stopping ||
                downloader.State == DownloaderState.PausedNetwork ||
                downloader.State == DownloaderState.PausedWaiting)
            {
                return DependencyProperty.UnsetValue;
            }
            return string.Format(BlockSizeFormat, ((double)downloader.Settings.BlockSize / KiloByte).ToString("N", nfi));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}